﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Data;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;

namespace KZ.Utilities
{
    public class SearchCriteria : Dictionary<string, object>
    {
    }

    public static class Utility
    {
        public static string AppPath;
        public static CultureInfo _INFO;
        public static string _CONNECT;

        public static int IntParse(object o)
        {
            int i;
            if (o == null || !int.TryParse(o.ToString(), out i))
                return 0;
            return i;
        }

        public static int? IntNParse(object o)
        {
            int i;
            if (o == null || !int.TryParse(o.ToString(), out i))
                return null;
            return i;
        }

        public static decimal DecimalParse(object o)
        {
            decimal d;
            if (o == null || !decimal.TryParse(o.ToString(), out d))
                return 0;
            return d;
        }

        public static decimal? DecimalNParse(object o)
        {
            decimal d;
            if (o == null || !decimal.TryParse(o.ToString(), out d))
                return null;
            return d;
        }

        public static string StringParse(object o)
        {
            return o + String.Empty;
        }

        public static string CurrencyParse(object o)
        {
            return o == null ? String.Empty : String.Format(_INFO, "{0:C}", o);
        }

        public static string NumberParse(object o)
        {
            return o == null ? String.Empty : String.Format(_INFO, "{0:N}", o);
        }

        public static DateTime DateTimeParse(object o)
        {
            if (o == null) return DateTime.MinValue;
            DateTime dt;
            DateTime.TryParse(o.ToString(), out dt);
            return dt;
        }

        public static T ToEntity<T>(this DataRow row)
        {
            T ent = Activator.CreateInstance<T>();
            PropertyInfo[] properties = typeof(T).GetProperties();
            foreach (PropertyInfo prp in properties)
            {
                if (row.Table.Columns.Contains(prp.Name))
                {
                    if (row[prp.Name] == DBNull.Value)
                        prp.SetValue(ent, null, null);
                    else
                        prp.SetValue(ent, row[prp.Name], null);
                }
            }

            return ent;
        }

        public static T ToEntity<T>(this string xml)
        {
            using (TextReader reader = new StringReader(xml))
            {
                T ent = default(T);
                ent = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                return ent;
            }
        }
    }
}
